# ==============================================================================
# {{cookiecutter.project_name}}
# ==============================================================================
#
# {{cookiecutter.project_description}}
#
# Tech Stack:
#   - Backend: FastAPI + Python {{cookiecutter.python_version}}+
{% if cookiecutter.database != "none" -%}
#   - Database: {{cookiecutter.database}}
{% endif -%}
{% if cookiecutter.ui_framework == "mui" -%}
#   - Frontend: React + TypeScript + Material-UI
{% elif cookiecutter.ui_framework == "tailwind" -%}
#   - Frontend: React + TypeScript + TailwindCSS
{% elif cookiecutter.ui_framework == "radix+tailwind" -%}
#   - Frontend: React + TypeScript + Radix UI + TailwindCSS
{% endif -%}
{% if cookiecutter.include_tauri == "yes" -%}
#   - Packaging: Tauri (native desktop app)
{% endif -%}
#
# Prerequisites:
#   - tmux        (for running dev servers in background)
#   - uv          (Python package manager)
#   - npm         (Node package manager)
#   - lsof        (for port checking)
#   - pgrep/pkill (for process management)
{% if cookiecutter.include_tauri == "yes" -%}
#   - cargo/rust  (for Tauri builds)
{% endif -%}
#
# Quick Start:
#   1. make install         # Install all dependencies
#   2. make dev-check       # Verify environment is ready
{% if cookiecutter.include_tauri == "yes" -%}
#   3. make dev-tauri       # Start Tauri desktop app
{% else -%}
#   3. make dev             # Start development servers
{% endif -%}
#
# ==============================================================================

# ------------------------------------------------------------------------------
# Configuration Variables
# ------------------------------------------------------------------------------

# Project metadata
PROJECT_NAME := {{cookiecutter.project_slug}}
APP_NAME := {{cookiecutter.project_name}}

# Python configuration
PYTHON_PATH := $(PWD)
PYTHON_CMD := uv run python
UVICORN_CMD := uv run uvicorn

# Backend configuration
BACKEND_PORT := {{cookiecutter.backend_port}}
BACKEND_HOST := localhost
BACKEND_MODULE := src.backend.api.main:app

# Frontend configuration
FRONTEND_PORT := {{cookiecutter.frontend_port}}
FRONTEND_HOST := 127.0.0.1
FRONTEND_DIR := src/frontend

{% if cookiecutter.include_tauri == "yes" -%}
# Tauri configuration
TAURI_DIR := src-tauri
TAURI_LOG := $(TAURI_DIR)/tauri-backend.log
APP_LOG := $(TAURI_DIR)/{{cookiecutter.project_slug}}.log

# Build configuration
DIST_DIR := dist
BUILD_DIR := build
SIDECAR_BINARY := {{cookiecutter.project_slug}}-backend
SIDECAR_TARGET := {{cookiecutter.project_slug}}-backend-aarch64-apple-darwin

{% endif -%}
# Development environment
TMUX_SESSION := $(PROJECT_NAME)

# Data directories
LOG_ARCHIVE_DIR := logs-archive

# Environment variables for Python execution
PYTHON_ENV := PYTHONPATH=$(PYTHON_PATH)

# ------------------------------------------------------------------------------
# Phony Targets (not actual files)
# ------------------------------------------------------------------------------
.PHONY: help install install-backend install-frontend dev dev-backend dev-frontend \
        dev-status dev-stop dev-clean dev-check \
{% if cookiecutter.include_tauri == "yes" -%}
        dev-tauri dev-tauri-logs \
{% endif -%}
        logs-status logs-tail logs-clear logs-archive logs-watch \
        test test-backend test-frontend lint format clean \
{% if cookiecutter.include_tauri == "yes" -%}
        build build-sidecar build-tauri
{% else -%}
        build
{% endif %}

# ------------------------------------------------------------------------------
# Help - Default target shows all available commands
# ------------------------------------------------------------------------------
help:
	@echo "$(APP_NAME) - Development Commands"
	@echo ""
	@echo "Setup:"
	@echo "  make install          - Install all dependencies (backend + frontend)"
	@echo "  make install-backend  - Install Python dependencies"
	@echo "  make install-frontend - Install Node dependencies"
	@echo ""
	@echo "Development:"
	@echo "  make dev              - Run both backend and frontend (requires tmux)"
	@echo "  make dev-backend      - Run FastAPI backend only"
	@echo "  make dev-frontend     - Run React frontend only"
{% if cookiecutter.include_tauri == "yes" -%}
	@echo "  make dev-tauri        - Run Tauri desktop app in dev mode"
{% endif -%}
	@echo "  make dev-status       - Check if development servers are running"
	@echo "  make dev-clean        - Kill ALL dev processes and clean locks"
	@echo "  make dev-check        - Show complete environment state (RECOMMENDED FIRST)"
	@echo ""
	@echo "Log Management:"
{% if cookiecutter.include_tauri == "yes" -%}
	@echo "  make dev-tauri-logs   - Stream Tauri backend logs in real-time"
{% endif -%}
	@echo "  make logs-status      - Show log files status (size, lines, age)"
	@echo "  make logs-tail        - Show last 50 lines with error highlighting"
	@echo "  make logs-watch       - Watch current logs in real-time"
	@echo "  make logs-clear       - Clear all log files"
	@echo "  make logs-archive     - Archive logs with timestamp"
	@echo ""
	@echo "Testing:"
	@echo "  make test             - Run all tests"
	@echo "  make test-backend     - Run backend tests only"
	@echo "  make test-frontend    - Run frontend tests only"
	@echo ""
	@echo "Code Quality:"
	@echo "  make lint             - Run linters (ruff + eslint)"
	@echo "  make format           - Format code (black + prettier)"
	@echo ""
	@echo "Distribution:"
{% if cookiecutter.include_tauri == "yes" -%}
	@echo "  make build-tauri      - Build Tauri desktop app (recommended)"
{% else -%}
	@echo "  make build            - Build frontend for production"
{% endif -%}
	@echo ""
	@echo "Cleanup:"
	@echo "  make clean            - Remove generated files and caches"

# ------------------------------------------------------------------------------
# Installation - Set up development environment
# ------------------------------------------------------------------------------

install: install-backend install-frontend

install-backend:
	@echo "Installing Python dependencies..."
	uv sync

install-frontend:
	@echo "Installing Node dependencies..."
	cd $(FRONTEND_DIR) && npm install

# ------------------------------------------------------------------------------
# Development Servers - Run application in development mode
# ------------------------------------------------------------------------------

dev:
	@echo "Starting backend and frontend in tmux..."
	@command -v tmux >/dev/null 2>&1 || { \
		echo "ERROR: tmux not found. Install tmux or run 'make dev-backend' and 'make dev-frontend' separately."; \
		exit 1; \
	}
	@echo "Cleaning up any existing sessions..."
	@tmux kill-session -t $(TMUX_SESSION) 2>/dev/null || true
	@echo "Creating new tmux session with backend and frontend..."
	tmux new-session -d -s $(TMUX_SESSION) -n dev
	tmux send-keys -t $(TMUX_SESSION):dev 'make dev-backend' C-m
	tmux split-window -h -t $(TMUX_SESSION):dev
	tmux send-keys -t $(TMUX_SESSION):dev.1 'make dev-frontend' C-m
	tmux select-pane -t $(TMUX_SESSION):dev.0
	@echo "Session created successfully!"
	@echo "To view logs: tmux attach-session -t $(TMUX_SESSION)"
	@if [ -t 0 ]; then \
		echo "Attaching to session... (Ctrl+B, D to detach)"; \
		tmux attach-session -t $(TMUX_SESSION); \
	else \
		echo "Non-interactive mode - tmux session running in background"; \
	fi

dev-backend:
	@echo "Starting FastAPI backend on http://$(BACKEND_HOST):$(BACKEND_PORT)..."
	$(PYTHON_ENV) $(UVICORN_CMD) $(BACKEND_MODULE) --reload --port $(BACKEND_PORT)

dev-frontend:
	@echo "Starting React frontend on http://$(FRONTEND_HOST):$(FRONTEND_PORT)..."
	cd $(FRONTEND_DIR) && npm run dev -- --host $(FRONTEND_HOST) --port $(FRONTEND_PORT)

{% if cookiecutter.include_tauri == "yes" -%}
dev-tauri:
	@echo "Starting Tauri development mode..."
	@if [ ! -f "start_tauri_dev.sh" ]; then \
		echo "ERROR: start_tauri_dev.sh not found"; \
		echo "Create this script to start your backend and Tauri dev mode"; \
		exit 1; \
	fi
	./start_tauri_dev.sh

{% endif -%}
dev-status:
	@echo "Checking development server status..."
	@echo ""
	@echo "=== Tmux Sessions ==="
	@tmux list-sessions 2>/dev/null || echo "No tmux sessions running"
	@echo ""
	@echo "=== Backend (Port $(BACKEND_PORT)) ==="
	@if lsof -ti:$(BACKEND_PORT) >/dev/null 2>&1; then \
		echo "✓ Backend is running on port $(BACKEND_PORT)"; \
		echo "Process: $$(ps -p $$(lsof -ti:$(BACKEND_PORT)) -o comm= 2>/dev/null || echo 'unknown')"; \
	else \
		echo "○ No process running on port $(BACKEND_PORT)"; \
	fi
	@echo ""
	@echo "=== Frontend (Port $(FRONTEND_PORT)) ==="
	@if lsof -ti:$(FRONTEND_PORT) >/dev/null 2>&1; then \
		echo "✓ Frontend is running on port $(FRONTEND_PORT)"; \
		echo "Process: $$(ps -p $$(lsof -ti:$(FRONTEND_PORT)) -o comm= 2>/dev/null || echo 'unknown')"; \
	else \
		echo "○ No process running on port $(FRONTEND_PORT)"; \
	fi

# ------------------------------------------------------------------------------
# Development Cleanup
# ------------------------------------------------------------------------------

dev-clean:
	@echo "=================================="
	@echo "  Comprehensive Dev Cleanup"
	@echo "=================================="
	@echo ""
	@echo "1. Killing tmux sessions..."
	@if tmux has-session -t $(TMUX_SESSION) 2>/dev/null; then \
		tmux kill-session -t $(TMUX_SESSION) && echo "   ✓ Killed tmux session '$(TMUX_SESSION)'"; \
	else \
		echo "   ○ No tmux session found"; \
	fi
	@echo ""
	@echo "2. Killing processes..."
{% if cookiecutter.include_tauri == "yes" -%}
	@for PROC in "uvicorn.*$(BACKEND_PORT)" "tauri" "cargo run" "vite.*dev" "npm.*dev"; do \
{% else -%}
	@for PROC in "uvicorn.*$(BACKEND_PORT)" "vite.*dev" "npm.*dev"; do \
{% endif -%}
		if pgrep -f "$$PROC" >/dev/null 2>&1; then \
			pkill -9 -f "$$PROC" && echo "   ✓ Killed $$PROC"; \
		fi; \
	done
	@echo ""
	@echo "3. Killing processes on ports..."
	@if lsof -ti:$(BACKEND_PORT) >/dev/null 2>&1; then \
		lsof -ti:$(BACKEND_PORT) | xargs kill -9 2>/dev/null && echo "   ✓ Killed process on port $(BACKEND_PORT)"; \
	else \
		echo "   ○ Port $(BACKEND_PORT) is free"; \
	fi
	@if lsof -ti:$(FRONTEND_PORT) >/dev/null 2>&1; then \
		lsof -ti:$(FRONTEND_PORT) | xargs kill -9 2>/dev/null && echo "   ✓ Killed process on port $(FRONTEND_PORT)"; \
	else \
		echo "   ○ Port $(FRONTEND_PORT) is free"; \
	fi
	@echo ""
	@echo "✓ Cleanup complete"

dev-check:
	@echo "=================================="
	@echo "  Development Environment Check"
	@echo "=================================="
	@echo ""
	@echo "1. Running Processes:"
{% if cookiecutter.include_tauri == "yes" -%}
	@TOTAL=$$(pgrep -f "uvicorn|tauri|vite|npm.*dev" | wc -l | tr -d ' '); \
{% else -%}
	@TOTAL=$$(pgrep -f "uvicorn|vite|npm.*dev" | wc -l | tr -d ' '); \
{% endif -%}
	if [ $$TOTAL -eq 0 ]; then \
		echo "   ○ No development processes running"; \
	else \
		echo "   ⚠ Found $$TOTAL development processes"; \
	fi
	@echo ""
	@echo "2. Port Status:"
	@if lsof -ti:$(BACKEND_PORT) >/dev/null 2>&1; then \
		echo "   ⚠ Port $(BACKEND_PORT) (backend): OCCUPIED"; \
	else \
		echo "   ✓ Port $(BACKEND_PORT) (backend): FREE"; \
	fi
	@if lsof -ti:$(FRONTEND_PORT) >/dev/null 2>&1; then \
		echo "   ⚠ Port $(FRONTEND_PORT) (frontend): OCCUPIED"; \
	else \
		echo "   ✓ Port $(FRONTEND_PORT) (frontend): FREE"; \
	fi
	@echo ""
	@echo "=================================="
	@echo "  Summary"
	@echo "=================================="
{% if cookiecutter.include_tauri == "yes" -%}
	@if ! pgrep -f "uvicorn|tauri|vite" >/dev/null 2>&1 && \
{% else -%}
	@if ! pgrep -f "uvicorn|vite" >/dev/null 2>&1 && \
{% endif -%}
	   ! lsof -ti:$(BACKEND_PORT) >/dev/null 2>&1 && \
	   ! lsof -ti:$(FRONTEND_PORT) >/dev/null 2>&1; then \
		echo "Status: READY"; \
		echo ""; \
{% if cookiecutter.include_tauri == "yes" -%}
		echo "Action: You can run 'make dev-tauri' or 'make dev'"; \
{% else -%}
		echo "Action: You can run 'make dev'"; \
{% endif -%}
	else \
		echo "Status: OCCUPIED"; \
		echo ""; \
		echo "Action: Run 'make dev-clean' first"; \
	fi
	@echo ""

# ------------------------------------------------------------------------------
# Log Management
# ------------------------------------------------------------------------------

{% if cookiecutter.include_tauri == "yes" -%}
dev-tauri-logs:
	@echo "Streaming Tauri backend logs (Ctrl+C to stop)..."
	@if [ ! -f "$(TAURI_LOG)" ]; then \
		echo "⚠ Log file not found: $(TAURI_LOG)"; \
		touch $(TAURI_LOG); \
	fi
	@tail -f $(TAURI_LOG)

logs-watch:
	@$(MAKE) dev-tauri-logs

logs-status:
	@echo "=================================="
	@echo "  Log Files Status"
	@echo "=================================="
	@echo ""
	@if [ -f "$(TAURI_LOG)" ]; then \
		SIZE=$$(du -h $(TAURI_LOG) | cut -f1); \
		LINES=$$(wc -l < $(TAURI_LOG) | tr -d ' '); \
		echo "✓ $(TAURI_LOG)"; \
		echo "  Size: $$SIZE"; \
		echo "  Lines: $$LINES"; \
	else \
		echo "○ $(TAURI_LOG): Not found"; \
	fi
	@echo ""

logs-tail:
	@echo "=================================="
	@echo "  Last 50 Lines (Errors Highlighted)"
	@echo "=================================="
	@if [ -f "$(TAURI_LOG)" ]; then \
		tail -50 $(TAURI_LOG) | grep --color=always -E 'ERROR|STDERR|Failed|Exception|$$'; \
	fi

logs-clear:
	@echo "Clearing all log files..."
	@if [ -f "$(TAURI_LOG)" ]; then \
		> $(TAURI_LOG) && echo "✓ Cleared $(TAURI_LOG)"; \
	fi
	@echo "Log files cleared."

logs-archive:
	@echo "Archiving logs with timestamp..."
	@mkdir -p $(LOG_ARCHIVE_DIR)
	@TIMESTAMP=$$(date +%Y%m%d_%H%M%S); \
	if [ -f "$(TAURI_LOG)" ]; then \
		cp $(TAURI_LOG) $(LOG_ARCHIVE_DIR)/tauri-backend_$$TIMESTAMP.log && \
		echo "✓ Archived to $(LOG_ARCHIVE_DIR)/tauri-backend_$$TIMESTAMP.log"; \
	fi
	@echo "Logs archived."
{% else -%}
logs-watch:
	@echo "Watching logs not available in web-only mode"
	@echo "Use 'make dev' and attach to tmux session instead"

logs-status:
	@echo "Log status not available in web-only mode"

logs-tail:
	@echo "Log tail not available in web-only mode"

logs-clear:
	@echo "Log clear not available in web-only mode"

logs-archive:
	@echo "Log archive not available in web-only mode"
{% endif %}

# ------------------------------------------------------------------------------
# Testing
# ------------------------------------------------------------------------------

test: test-backend test-frontend

test-backend:
	@echo "Running backend tests..."
	uv run pytest

test-frontend:
	@echo "Running frontend tests..."
	cd $(FRONTEND_DIR) && npm run test

# ------------------------------------------------------------------------------
# Code Quality
# ------------------------------------------------------------------------------

lint:
	@echo "Running linters..."
	@echo "Backend (ruff)..."
	uv run ruff check src/
	@echo "Frontend (eslint)..."
	cd $(FRONTEND_DIR) && npm run lint

format:
	@echo "Formatting code..."
	@echo "Backend (black)..."
	uv run black src/
	@echo "Frontend (prettier)..."
	cd $(FRONTEND_DIR) && npm run format

# ------------------------------------------------------------------------------
# Build and Distribution
# ------------------------------------------------------------------------------

{% if cookiecutter.include_tauri == "yes" -%}
build-sidecar:
	@echo "Building Python backend sidecar..."
	@mkdir -p $(TAURI_DIR)/binaries
	$(PYTHON_ENV) uv run pyinstaller {{cookiecutter.project_slug}}-sidecar.spec --clean --noconfirm
	@cp $(DIST_DIR)/$(SIDECAR_BINARY) $(TAURI_DIR)/binaries/$(SIDECAR_TARGET)
	@chmod +x $(TAURI_DIR)/binaries/$(SIDECAR_TARGET)
	@echo "Sidecar built and placed in $(TAURI_DIR)/binaries/"

build-tauri: build-sidecar
	@echo "Building Tauri desktop app..."
	cd $(FRONTEND_DIR) && npm run build
	cd $(TAURI_DIR) && source ~/.cargo/env && npx @tauri-apps/cli build

build: build-tauri
{% else -%}
build:
	@echo "Building frontend for production..."
	cd $(FRONTEND_DIR) && npm run build
	@echo "Build complete. Output in $(FRONTEND_DIR)/dist/"
{% endif %}

# ------------------------------------------------------------------------------
# Cleanup
# ------------------------------------------------------------------------------

clean:
	@echo "Cleaning generated files..."
	find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
	find . -type d -name "*.egg-info" -exec rm -rf {} + 2>/dev/null || true
	find . -type d -name ".pytest_cache" -exec rm -rf {} + 2>/dev/null || true
	find . -type f -name "*.pyc" -delete
{% if cookiecutter.include_tauri == "yes" -%}
	rm -rf $(DIST_DIR)/ $(BUILD_DIR)/
{% endif -%}
	rm -rf $(FRONTEND_DIR)/dist/ $(FRONTEND_DIR)/node_modules/.cache/
	@echo "Clean complete"
